import 'dart:async';
import 'dart:io';

import 'package:flutter_app/bean/task_detail_entity.dart';
import 'package:flutter_app/manager/UserInfoManager.dart';
import 'package:flutter_app/network/Api.dart';
import 'package:flutter_app/network/ResultData.dart';
import 'package:flutter_app/ui/collect/photo_gallery/photo_gallery_view.dart';
import 'package:flutter_app/utils/DialogUtils.dart';
import 'package:flutter_app/utils/EventBusUtils.dart';
import 'package:flutter_app/utils/image_file_info_utils.dart';
import 'package:flutter_app/utils/path_provider_utils.dart';
import 'package:flutter_app/utils/toast_utils.dart';
import 'package:flutter_app/widget/watermark/watermark_utils.dart';
import 'package:get/get.dart';
import 'package:image_pickers/image_pickers.dart';

import '../../../r.dart';
import '../query_list2/query_list_view.dart';
import 'collect_detail_state.dart';
import 'horizontal_image/horizontal_image_view.dart';

class CollectDetailLogic extends GetxController {
  final CollectDetailState state = CollectDetailState();

  late String groupId; // 任务id

  late StreamSubscription<CollectAddNum> collectAddNum;

  late bool addNum = false; // 是否需要刷新数据，问题详情页面修改了数据就需要，没有修改就不需要

  @override
  void onInit() {
    super.onInit();
    groupId = Get.arguments ?? "";
  }

  @override
  void onReady() {
    super.onReady();
    getTaskDetail();
    getDirFile();
    // 监听bus
    collectAddNum = bus.listen((event) => addNum = true);

    WatermarkUtils().addWatermark(Get.context!, UserInfoManager().getUserName());

    // 任务状态 添加默认值
    state.taskStatus = R.assetsImgIcon17;
  }

  /// 获取任务详情
  Future<void> getTaskDetail() async {
    Map<String, dynamic> param = {
      "id": groupId,
    };
    ResultData resultData = await Api.getTaskDetail(param);

    if (resultData.isSuccess) {
      state.taskDetailEntity = TaskDetailEntity.fromJson(resultData.data['data']);
      initData();
    } else {
      toast.show(resultData.data["message"]);
    }
  }

  /// 确认问题
  Future<bool> postConfirmTask(String id) async {
    Map<String, dynamic> param = {
      "id": id,
    };
    ResultData resultData = await Api.postConfirmTask(param);
    if (resultData.isSuccess) {
      // 删除当前任务 本地照片和视频
      deleteFile();
      //  根据返回结束 刷新首页
      if (resultData.data["data"] == "1") {
        bus.fire(DynamicEvent());
      }
      return true;
    } else {
      toast.show(resultData.data["message"]);
      return false;
    }
  }

  /// 完成填报
  Future<bool> postSubmitConfirmTask(String id) async {
    Map<String, dynamic> param = {
      "id": id,
    };
    ResultData resultData = await Api.postSubmitConfirmTask(param);
    if (resultData.isSuccess) {
      // 删除当前任务 本地照片和视频
      deleteFile();
      return true;
    } else {
      toast.show(resultData.data["message"]);
      return false;
    }
  }

  /// 初始化数据
  void initData() {
    // 任务状态 返回进行中或者已完成图标
    state.taskStatus = state.taskDetailEntity?.taskStatus == "0"
        ? R.assetsImgIcon17
        : R.assetsImgIcon34;
    // 任务名称
    state.taskTitle = state.taskDetailEntity?.taskTitle ?? "";
    // 任务开始时间
    state.startTime = state.taskDetailEntity?.startTime ?? "";
    // 任务路线
    state.areaName = state.taskDetailEntity?.collectGroupVO?.areaName ?? "";
    // 暗访单位
    state.organListName = getOrganListName();
    // 小组组长
    state.leaderName = getMemberListUserName(1);
    // 组员
    state.groupName = getMemberListUserName(2);
    //小组成员数量
    state.groupNum = state.taskDetailEntity?.collectGroupVO?.groupMemberVOList?.length ?? 0 ;
    // 已完成数量
    state.finishedNum = getFinishedNum();
    update();
  }


  /// 获取 所有的暗访单位 中间 以 、 进行拼接
  String getOrganListName() {
    String organListName = "";
    state.taskDetailEntity?.collectGroupVO?.routeVO?.organVOList?.forEach((element) {
      organListName += element.orgName! + "、";
    });
    return organListName.substring(0, organListName.length - 1);
  }

  /// 获取 对应成员列表的用户名  中间 以 、 进行拼接
  /// type 1 获取组长   2获得小组成员
  String getMemberListUserName(int type){
    String memberListUserName = "";
    List<TaskDetailCollectGroupVOGroupMemberVOList>? groupMemberVOList = state.taskDetailEntity!.collectGroupVO!.groupMemberVOList!;
    if (type == 1) {
      memberListUserName = groupMemberVOList.first.userName!;
    } else {
      if (groupMemberVOList.length > 1) {
        for (int i = 1; i < groupMemberVOList.length; i++) {
          memberListUserName += groupMemberVOList[i].userName! + "、";
        }
        memberListUserName = "、" + memberListUserName.substring(0, memberListUserName.length - 1);
      }
    }
    return memberListUserName;
  }

  /// 获取完成数量
  int getFinishedNum() {
    int num = 0;
    state.taskDetailEntity!.collectGroupVO!.groupMemberVOList!.forEach((element) {
      if (element.status == '2') {
        num++;
      }
    });
    return num;
  }

  ///
  /// list 列表 状态文字描述
  /// writeAuth 	是否有填报权限  0没有 1有
  /// status	    0待上传 1待确认 2已确认
  ///
  String getMemberState(String status) {
    String str = "";
    switch (status) {
      case "0":
        str = "填报中";
        break;
      case "1":
        str = "待确认";
        break;
      default:
        str = "已完成填报";
        break;
    }
    return str;
  }

  ///
  /// writeAuth  是否有填报权限  0没有 1有
  /// memberRole 0组员 1组长
  /// 组长 确认按钮 显示 problemSubmitList.size > 0
  ///                               memberStatus  = 0    完成填报   可点击
  ///                               memberStatus  = 2    已完成填报  不可点击
  /// 成员 确认按钮 显示  problemSubmitList.size > 0
  ///                               memberStatus = 0    待完成填报   不可点击
  ///                                memberStatus = 1    确认问题   可点击
  ///                                 memberStatus = 2    已确认问题   不可点击
  ///
  /// 获得底部按钮是否显示
  /// 返回 true显示  false 不显示
  ///
  bool getButtonShow() {
    if ((state.taskDetailEntity?.orgProblemList!.length ?? 0) > 0) {
      return true;
    } else {
      return false;
    }
  }

  /// 获得底部按钮 显示 的文字
  /// 返回  底部按钮 显示 的文字
  String getButtonText() {
    String str = "";
    if (state.taskDetailEntity?.memberRole == "1") {
      switch (state.taskDetailEntity?.memberStatus) {
        case "0":
          str = "完成填报";
          break;
        case "2":
          str = "已确认问题";
          break;
        default:
          str = "";
          break;
      }
    } else {
      switch (state.taskDetailEntity?.memberStatus) {
        case "0":
          str = "待完成填报";
          break;
        case "1":
          str = "确认问题";
          break;
        case "2":
          str = "已确认问题";
          break;
        default:
          str = "";
          break;
      }
    }
    return str;
  }

  /// 获得按钮点击状态
  /// 返回  true 可以点击  false 不可点击
  bool getButtonClickState() {
    if (state.taskDetailEntity?.memberRole == "1") {
      if (state.taskDetailEntity?.memberStatus == "0") {
        return true;
      } else {
        return false;
      }
    } else {
      if (state.taskDetailEntity?.memberStatus == "1") {
        return true;
      } else {
        return false;
      }
    }
  }

  /// 点击按钮
  void confirmTask() {
    String? id = state.taskDetailEntity?.collectGroupVO?.id ?? "";
    String title = "";
    String content = "";
    bool isWriteAuth = false; // 是否是组长  true 是 false 不是
    if (state.taskDetailEntity?.memberRole == "0") {
      title = "确认没问题？";
      content = "确认后表示您认可所有成员填报问题，所有组员确认后将自动上报至效能办";
      isWriteAuth = false;
    } else {
      title = "确认完成填报";
      content = "确认后将提交已填报内容，其余组员确认后将自动上报至效能办";
      isWriteAuth = true;
    }
    dialogUtils.show(
      context: Get.context!,
      title: title,
      content: content,
      callbackOk: () {
        if (isWriteAuth) {
          // 完成填报
          postSubmitConfirmTask(id).then((value) {
            if (value) {
              getTaskDetail().then((_) {
                /// 发送通知 通知
                busFire();
              });
            }
          });
        } else {
          // 确认问题
          postConfirmTask(id).then((value) {
            if (value) {
              getTaskDetail().then((_) {
                /// 发送通知 通知
                busFire();
              });
            }
          });
        }
      },
    );
  }

  // groupId 小组id 用来判断是哪一条数据
  // taskStatus 任务状态 用来显示
  // memberStatus 自身状态0未上传1待确认2已确认
  // totalProblem 上报问题数量

  /// 发送通知 通知
  busFire() {
    //  taskStatus  0进行中 1已完成   writeAuth	是否可以填报0否1是 memberStatus 自身状态0未上传1待确认2已确认
    bus.fire(CollectDetailEvent(
      groupId,
      state.taskDetailEntity?.taskStatus ?? "",
      state.taskDetailEntity?.memberStatus ?? "",
      state.taskDetailEntity?.problemCount.toString() ?? "",
    ));
  }

  // 跳转 问题填报页面
  void goToCollectTaskPage(int index, {int? organIndex} ) {
    // 跳转页面时，先把标记设置为false
    addNum = false;
    String? orgId = "", orgName = "";
    if (organIndex != null) {
      orgId = state.taskDetailEntity?.orgProblemList?[index].organList?[organIndex].orgId;// 单位ID
      orgName = state.taskDetailEntity?.orgProblemList?[index].organList?[organIndex].orgName;
    } else {
      orgId = state.taskDetailEntity?.orgProblemList?[index].orgId; // 单位ID
      orgName = state.taskDetailEntity?.orgProblemList?[index].orgName; // 单位ID
    }

    print("orgId = $orgId");
    Get.to(() => QueryListPage(
        title: orgName ?? "",
      ),
      arguments: {
        "groupId": groupId, // 小组id
        "orgId": orgId, // 单位ID
        "memberStatus": state.taskDetailEntity?.memberStatus, // 成员自身状态0待填报1待确认2已确认
      },
    )?.then((value) {
      if (addNum) {
        getTaskDetail().then((value) {
          /// 发送通知 通知
          busFire();
        });
      }
    });
  }

  /// 判断是否有二级单位列表
  bool getOrganListLength(int index) {
    return (state.taskDetailEntity?.orgProblemList?[index].organList?.length ?? 0) > 0 ? true : false;
  }

  /// 获取 二级单位列表
  List<TaskDetailOrgProblemListOrganList>? getOrganList(int index) {
    return state.taskDetailEntity?.orgProblemList?[index].organList;
  }

  /// 获取 所有的暗访单位 中间 以 、 进行拼接
  String listToString(List<dynamic>? list) {
    String str = "";
    if (list?.length == 0) {
      return str;
    }
    list?.forEach((element) {
      str += element.toString() + "、";
    });
    return str.substring(0, str.length - 1);
  }

  // 跳转 可视化采集资料 全部
  void goToPhotoGalleryPage() {
    Get.to(() => PhotoGalleryPage(title: "可视化采集资料"), arguments: groupId)?.then((value) async {
      state.list.clear();
      await getDirFile();
      horizontalImageKey.currentState?.update();
    });
  }


  // 获取指定文件夹下的 图片和视频
  Future<void> getDirFile() async {
    List<ImageFileInfo> imageFileInfo = await ImageFileInfoUtils().getFileInfoInGroupId(groupId);
    List<Media> list = [];
    imageFileInfo.forEach((element) {
      Media media = new Media();
      media.path = element.path;
      media.address = element.address;
      media.dateTime = element.dateTime;
      media.thumbPath = element.thumbnail;
      if (element.type == "image") {
        media.galleryMode = GalleryMode.image;
      } else {
        media.galleryMode = GalleryMode.video;
      }
      list.add(media);
    });
    state.list.addAll(list);
    update();
  }

  // 完成填报后 删除 本地 清除相对应的json
  Future<void> deleteFile() async {
    String path = await PathProviderUtils().getTempDir() + Platform.pathSeparator + groupId;

    bool exists = Directory(path).existsSync();
    if (exists) {
      PathProviderUtils().delDir(Directory(path));
    }

    await ImageFileInfoUtils().deleteInGroupId(groupId);

  }

  @override
  void onClose() {
    super.onClose();
    WatermarkUtils().removeWatermark();
  }
}
